/*
 * 文件名：ProgramPlanController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：chenhan
 * 修改时间：2020年1月13日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.ic.web;


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.bpa.service.ProContractService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.ic.domain.ProgramPlanDomain;
import top.infopub.mgr.ic.service.BuildInfoService;
import top.infopub.mgr.ic.service.BuildSubService;
import top.infopub.mgr.ic.service.ProgramPlanAttService;
import top.infopub.mgr.ic.service.ProgramPlanMileService;
import top.infopub.mgr.ic.service.ProgramPlanService;
import top.infopub.mgr.ic.service.ProgramPlanSubService;
import top.infopub.mgr.ic.vo.ProgramPlanMileVo;
import top.infopub.mgr.ic.vo.ProgramPlanVo;
import top.infopub.mgr.util.DateUtils;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.model.bpa.ProContract;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.ic.BuildInfo;
import top.infopub.model.ic.BuildSub;
import top.infopub.model.ic.ProgramPlan;
import top.infopub.model.ic.ProgramPlanAtt;
import top.infopub.model.ic.ProgramPlanMile;
import top.infopub.model.ic.ProgramPlanSub;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.github.pagehelper.Page;


/**
 * 项目工程计划
 *
 * @author chenhan
 * @version 2020年1月13日
 * @see ProgramPlanController
 * @since
 */
@Controller
@RequestMapping("/programPlan")
public class ProgramPlanController extends GenericFlowController {

    @Autowired
    private ProgramPlanService programPlanService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private BuildInfoService buildInfoService;

    @Autowired
    private BuildSubService buildSubService;

    @Autowired
    private ProgramPlanAttService programPlanAttService;

    @Autowired
    private ProgramPlanSubService programPlanSubService;

    @Autowired
    private ProgramPlanMileService programPlanMileService;

    @Autowired
    private ProContractService proContractService;

    /**
     * 项目工程计划列表
     *
     * @return
     * @see
     */
    @RequestMapping("/list")
    public String list() {
        return "ic/lay-programPlan-list";
    }

    /**
     * 建投项目管理列表
     *
     * @param programPlanVo
     * @param paramPage
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ProgramPlanDomain> queryDataByCondition(ProgramPlanVo programPlanVo,
                                                         ParamPage paramPage) {
        Page<ProgramPlanDomain> page = new Page<>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        if (programPlanVo.getEndDate() != null) {
            programPlanVo.setEndDate(DateUtils.addDays(programPlanVo.getEndDate(), 1));
        }
        page = programPlanService.selectByDomainWhere(page, programPlanVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 查询我审批的项目工程计划
     *
     * @param programPlanVo
     * @param paramPage
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<ProgramPlanDomain> queryMyCheckDataByCondition(ProgramPlanVo programPlanVo,
                                                                ParamPage paramPage) {
        Page<ProgramPlanDomain> page = new Page<>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (programPlanVo.getEndDate() != null) {
            programPlanVo.setEndDate(DateUtils.addDays(programPlanVo.getEndDate(), 1));
        }

        // 增加addby
        programPlanVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = programPlanService.selectMyCheckByDomainWhere(page, programPlanVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 新增
     *
     * @param request
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //返回所有投建项目的项目名称
        BuildInfo buildInfo = new BuildInfo();
        buildInfo.setProcessStatus("9");
        List<BuildInfo> buildInfoList = buildInfoService.selectByEntityWhere(buildInfo);
        request.setAttribute("buildInfoList", buildInfoList);
        return "ic/lay-programPlan-add";
    }

    /**
     * 通过项目id查询记录
     */
    @RequestMapping("/getBuildInfoById")
    @ResponseBody
    public Map<String, Object> getProPlotProId(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String buildInfoId = request.getParameter("buildInfoId");
            BuildInfo buildInfo = buildInfoService.selectByPrimaryKey(buildInfoId);
            if (buildInfo != null) {
                Map<String, Object> mapWhere = new HashMap<String, Object>();
                mapWhere.put("proCode", buildInfo.getProCode());
                mapWhere.put("processStatus", "9");
                mapWhere.put("orderCondition", "ADD_TIME desc");
                List<BuildInfo> buildInfos = buildInfoService.selectByMapWhere(mapWhere);
                if(CollectionUtils.isNotEmpty(buildInfos)){
                    buildInfo = buildInfos.get(0);
                    map.put("buildInfo", buildInfos.get(0));
                }else{
                    map.put("buildInfo", buildInfo);
                }
                //查询子项信息列表
                BuildSub buildSub = new BuildSub();
                buildSub.setBuildInfoId(buildInfo.getId());
                List<BuildSub> buildSubList = buildSubService.selectByEntityWhere(buildSub);
                if (CollectionUtils.isNotEmpty(buildSubList)) {
                    //先只返回一个子项信息
                    map.put("buildSubList", buildSubList);
                }
            }
        }
        catch (Exception e) {
            log.error("根据投建项目ID获取项目信息异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 项目工程计划-新增
     *
     * @throws ParseException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(HttpServletRequest request, ProgramPlan programPlan)
        throws ParseException {
        String buildInfoId = request.getParameter("buildInfoId");
        //根据buildInfoId查proCode字段
        BuildInfo buildInfo = buildInfoService.selectByPrimaryKey(buildInfoId);
        programPlan.setProCode(buildInfo.getProCode());
        programPlan.setSgCityId(buildInfo.getSgCityId());
        programPlan.setProName(buildInfo.getProName());
        //id置空
        programPlan.setId("");
        //buildSub带入字段
        String[] subIdArray = request.getParameterValues("subId");
        String[] subNameArray = request.getParameterValues("subName");
        String[] orderIdxArray = request.getParameterValues("orderIdx");

        //获取节点各字段信息
        String[] showOrderIdxeArray = request.getParameterValues("showOrderIdx");
        //用planSubId存buildSub的Id
        String[] planSubIdArray = request.getParameterValues("planSubId");
        String[] mileNameArray = request.getParameterValues("mileName");
        String[] levelIdxeArray = request.getParameterValues("levelIdx");
        String[] memoArray = request.getParameterValues("memo");
        String[] planStartTimeArray = request.getParameterValues("planStartTime");
        String[] planFinishTimeArray = request.getParameterValues("planFinishTime");
        //数据处理
        List<ProgramPlanMile> planMileList = new LinkedList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < planSubIdArray.length; i++ ) {
            ProgramPlanMile programPlanMile = new ProgramPlanMile();
            //用programPlanMile表的PlanSubId存储buildSub的id,用作后续处理
            programPlanMile.setPlanSubId(planSubIdArray[i]);
            programPlanMile.setShowOrderIdx(showOrderIdxeArray[i]);
            programPlanMile.setLevelIdx(Integer.parseInt(levelIdxeArray[i]));
            programPlanMile.setMileName(mileNameArray[i]);
            programPlanMile.setMemo(memoArray[i]);
            if (null != planStartTimeArray[i] && planStartTimeArray[i].length() > 0) {
                programPlanMile.setPlanStartTime(simpleDateFormat.parse(planStartTimeArray[i]));
            }
            if (null != planFinishTimeArray[i] && planFinishTimeArray[i].length() > 0) {
                programPlanMile.setPlanFinishTime(simpleDateFormat.parse(planFinishTimeArray[i]));
            }
            planMileList.add(programPlanMile);
        }

        List<ProgramPlanSub> programPlanSubList = new LinkedList<>();
        for (int i = 0; i < subIdArray.length; i++ ) {
            ProgramPlanSub programPlanSub = new ProgramPlanSub();
            //用programPlanSub表的AddBy字段存储buildSub的id，用作后续处理
            programPlanSub.setAddBy(subIdArray[i]);
            programPlanSub.setSubName(subNameArray[i]);
            programPlanSub.setSubOrderIdx(Integer.parseInt(orderIdxArray[i]));
            programPlanSubList.add(programPlanSub);
        }

        String[] fileAtt = request.getParameterValues("fileAtt20");
        if (fileAtt == null || fileAtt.length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("工程计划附件上传");
        }
        programPlanService.saveProgramPlan(programPlan, planMileList, programPlanSubList, fileAtt);
        return RspVo.getSuccessResponse();
    }

    /**
     * 上传附件
     *
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "programPlanAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD,
                    "项目工程计划附件-文件名:" + filePath + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询项目工程计划详情  > 注意：方法命名必须为：toDealOrDetail
     *
     * @param id 预立项Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<>();
        ProgramPlanDomain programPlanDomain = programPlanService.selectById(id);
        //设置业态类型
        String formatType = programPlanDomain.getFormatType();
        switch (Integer.parseInt(formatType)) {
            case 1:
                programPlanDomain.setFormatTypeName("房建");
                break;
            case 2:
                programPlanDomain.setFormatTypeName("市政");
                break;
            case 3:
                programPlanDomain.setFormatTypeName("桥梁");
                break;
            case 4:
                programPlanDomain.setFormatTypeName("隧道");
                break;
            case 5:
                programPlanDomain.setFormatTypeName("管廊");
                break;
            case 6:
                programPlanDomain.setFormatTypeName("生态景观");
                break;
            default:
                programPlanDomain.setFormatTypeName("");
        }
        request.setAttribute("modelDetail", programPlanDomain);
        if (programPlanDomain.getBuildYears() == null || programPlanDomain.getOmYears() == null) {
            //建设期(年)/运营期(年)
            ProContract proContract = new ProContract();
            proContract.setProCode(programPlanDomain.getProCode());
            proContract.setProcessStatus("9");
            List<ProContract> proContractList = proContractService.selectByEntityWhere(proContract);
            if (proContractList != null && proContractList.size() > 0) {
                proContract = proContractList.get(0);
                programPlanDomain.setBuildYears(proContract.getBuildYears());
                programPlanDomain.setOmYears(proContract.getOmYears());
            }
        }
        //主表
        map.put("programPlan", programPlanDomain);
        //附件
        ProgramPlanAtt programPlanAtt = new ProgramPlanAtt();
        programPlanAtt.setProgramPlanId(id);
        List<ProgramPlanAtt> planAttList = programPlanAttService.selectByEntityWhere(programPlanAtt);
        map.put("planAttList", planAttList);

        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, programPlanDomain.getProcessId());
        return new ModelAndView("ic/lay-programPlan-detail", map);
    }
    
    /**
     * 复制单据
     * @param request
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request,String id) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        ProgramPlan programPlan = programPlanService.selectByPrimaryKey(id);
        request.setAttribute("programPlan", programPlan);
        //附件
        ProgramPlanAtt programPlanAtt = new ProgramPlanAtt();
        programPlanAtt.setProgramPlanId(id);
        List<ProgramPlanAtt> planAttList = programPlanAttService.selectByEntityWhere(programPlanAtt);
        request.setAttribute("planAttList", planAttList);
        return "ic/lay-programPlan-copy";
    }

    /**
     * 根据id查询子项
     *
     * @param id
     * @return
     * @see
     */
    @RequestMapping("/selectSubsById")
    @ResponseBody
    public RspVo<ProgramPlanSub> selectSubsById(String id) {
        ProgramPlanSub t = new ProgramPlanSub();
        t.setProgramPlanId(id);
        List<ProgramPlanSub> subs = programPlanSubService.selectByEntityWhere(t);
        return RspVo.getSuccessResponse(0, subs);
    }

    /**
     * 根据子项id查询里程碑
     *
     * @param id
     * @return
     * @see
     */
    @RequestMapping("/selectMilesById")
    @ResponseBody
    public RspVo<ProgramPlanMileVo> selectMilesById(String id) {
        List<ProgramPlanMileVo> miles = programPlanMileService.selectBySubId(id);
        return RspVo.getSuccessResponse(0, miles);
    }

}
